<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;

class Order extends Controller
{
    /**
     * 显示资源列表
     */
    public function index()
    {
        $page = input('get.page',1);
        $numPage = 5;
        $startPage = ($page-1) * $numPage;
        $data = db('order')->alias('o')->field('o.number,os.name,os.tel,os.address,o.total,o.status,o.addTime,o.id')->join('order_site os','o.id = os.orid')->limit($startPage,$numPage)->select();
        $count = db('order')->count();
        $pages = ceil(($count/$numPage));
        $this->assign('page',$page);
        $this->assign('pages',$pages);
        $this->assign('data',$data);
        $this->assign('count',$count);
        return view();
    }

    /**
     * 改变商品状态
     */
    public function status(){
        $data['id'] = input('post.id/d','');
        $data['status'] = input('post.status/d','');
        if(!$data['id']) return json(['status'=>0,'msg'=>'请选择要更新的状态!']);
        if($data['status'] == 1){
            $data['status'] = 2;
            return db('Order')->update($data) ? json(['status'=>1]) : json(['status'=>0,'msg'=>'该操作暂不可执行!']);
        }
        if($data['status'] == 2){
            $numInfo = db('order_commodity')->field('coid,num')->where(['orid'=>$data['id']])->select();
            foreach ($numInfo as $v){
                db('commodity')->where('id', $v['coid'])->setDec('stock', $v['num']);
            }
            $data['status'] = 3;
            return db('Order')->update($data) ? json(['status'=>2]) : json(['status'=>0,'msg'=>'该操作暂不可执行!']);
        }
        if($data['status'] == 3){
            $data['status'] = 4;
            return db('Order')->update($data) ? json(['status'=>3]) : json(['status'=>0,'msg'=>'该操作暂不可执行!']);
        }
        if($data['status'] == 4){
            $data['status'] = 5;
            return db('Order')->update($data) ? json(['status'=>4]) : json(['status'=>0,'msg'=>'该操作暂不可执行!']);
        }
        if($data['status'] == 5){
            $data['status'] = 6;
            return db('Order')->update($data) ? json(['status'=>5]) : json(['status'=>0,'msg'=>'该操作暂不可执行!']);
        }

    }

    // 订单详情
    public function lists()
    {
        $id = input('get.id/d','');
        $data = db('order')->alias('o')->field('o.number,os.name,os.tel,os.address,o.total,o.status,o.addTime')->join('order_site os','o.id = os.orid')->where(['o.id'=>$id])->find();
        $datas = db('commodity')->alias('c')->field('c.image,oc.name,c.hid,oc.price,oc.num,oc.sum')->join('order_commodity oc', 'oc.coid = c.id')->where(['oc.orid'=>$id])->select();
        foreach ($datas as $k=>$v){
            $img = explode('|',$v['image']);
            $datas[$k]['image'] = array_shift($img);
        }
        $this->assign('data',$data);
        $this->assign('datas',$datas);
        return view();
    }
}
